<?php

namespace App\Admin\Utils;

class Utils
{
    protected $appid;

    protected $apikey;

    public function __construct()
    {
        $this->appid = env('IHUYI_APPID');
        $this->apikey = env('IHUYI_APIKEY');
    }

    /**
     * 发送短信
     */
    public function sendSMS ($mobile, $content)
    {
        $url = 'https://106.ihuyi.com/webservice/sms.php?method=Submit';
        $data = "account={$this->appid}&password={$this->apikey}&mobile={$mobile}&content={$content}&format=json";

        $result = $this->initCURL($url, $data);

        return json_decode($result, true);
    }

    /**
     * 添加短信模板
     */
    public function addTemplate($content)
    {
        $url = 'http://106.ihuyi.com/webservice/sms.php?method=AddTemplate';
        $data = "account={$this->appid}&password={$this->apikey}&content={$content}&format=json";

        $result = $this->initCURL($url, $data);

        return json_decode($result, true);
    }

    /**
     * 查询短信余额
     */
    public function balanceTheQuery()
    {
        $url = 'http://106.ihuyi.com/webservice/sms.php?method=GetNum';
        $data = "account={$this->appid}&password={$this->apikey}&format=json";
        $result = $this->initCURL($url, $data);
        return json_decode($result, true);
    }

    private function initCURL ($url, $data) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        $return_str = curl_exec($curl);

        return $return_str;
    }
}
